package com.ltmall.api.manager.impl;

import com.ltmall.api.bean.ClientAccount;
import com.ltmall.api.dao.IClientAccountDAO;
import com.ltmall.api.manager.ClientAccountManager;
import com.wuwangkeji.homeflavor.enums.AccountPointChangeEnum;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Date;

public class ClientAccountManagerImpl implements ClientAccountManager {

    final private static Logger logger = LogManager.getLogger(ClientAccountManager.class);

    private IClientAccountDAO   iClientAccountDAO;

    @Override
    public ClientAccount getClientAccount(int userID) {
        return iClientAccountDAO.getClientAccount(userID);
    }

    @Override
    public boolean updateAccountPoint(int userID, int point, AccountPointChangeEnum change) {

        //【1】查询用户是否存在
        ClientAccount clientAccount = iClientAccountDAO.getClientAccount(userID);
        if (clientAccount == null) {
            logger.error("更新用户积分时，发现该用户账户信息不存在，userid：" + userID);
            return false;
        }

        //更新前积分
        int prePoint = clientAccount.getPoint();

        //【2】积分增加时的情况
        if ((AccountPointChangeEnum.POINT_UP).equals(change))
            prePoint += point;

        //【3】积分减少时的情况
        if ((AccountPointChangeEnum.POINT_DOWN).equals(change)) {
            //更新前积分小于本次需要减少的积分时，返回失败
            if (point > prePoint)
                return false;
            else
                prePoint -= point;
        }

        //【4】更新积分
        boolean result = iClientAccountDAO.updateAccountPoint(userID, prePoint);
        if (!result)
            logger.warn("更新用户积分失败，userid：" + userID);

        return result;
    }
    
    @Override
    public boolean updateExpiration(int userID, Date expiration) {
        return iClientAccountDAO.updateExpiration(userID, expiration);
    }

    /**
     * @param iClientAccountDAO the iClientAccountDAO to set
     */
    public void setiClientAccountDAO(IClientAccountDAO iClientAccountDAO) {
        this.iClientAccountDAO = iClientAccountDAO;
    }

    
}
